package org.dkakunsi.aplikasitoko.data.adapter;

import java.util.List;

import org.dkakunsi.aplikasitoko.data.access.TransaksiDataAccess;
import org.dkakunsi.aplikasitoko.data.entity.Transaksi;
import org.dkakunsi.aplikasitoko.data.util.ApplicationDataException;
import org.dkakunsi.aplikasitoko.data.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class TransaksiDataAdapter implements TransaksiDataAccess {

	private Session session;
	private Transaction tx;
	
	public TransaksiDataAdapter() {
		this.session = HibernateUtil.openSession();
		this.tx = session.beginTransaction();
	}
	
	public TransaksiDataAdapter(Session session) {
		this.session = session;
		this.tx = session.beginTransaction();
	}

	@Override
	public void save(Object object) throws ApplicationDataException {
		Transaksi transaksi = null;
		
		try {
			transaksi = (Transaksi) object;
			
			session.save(transaksi);
			tx.commit();
		} catch(ConstraintViolationException x) {
			throw new ApplicationDataException("Duplikasi data untuk KODE : " +transaksi.getKode());
		}
	}

	@Override
	public void update(Object object) throws Exception {
		Transaksi transaksi = (Transaksi) object;
		
		session.merge(transaksi);
		tx.commit();
	}

	@Override
	public void delete(Object object) throws Exception {
		Transaksi transaksi = (Transaksi) object;
		
		session.delete(transaksi);
		tx.commit();
	}

	@Override
	public Object getByID(String id) throws ApplicationDataException {
		Transaksi transaksi= (Transaksi) session.get(Transaksi.class, id);
		tx.commit();
		
		if(transaksi != null){
			return transaksi;
		} else {
			throw new ApplicationDataException("File Not Found");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Transaksi> getAll(String type) throws Exception {
		List<Transaksi> all = null;
		
		Session session = HibernateUtil.openSession();
		
		if(type.equals("TRANSAKSI")){
			all = session.createQuery("from Transaksi order by KODE").list();
		} else if(type.equals("PEMBELIAN")){
			all = session.createQuery("from Pembelian order by KODE").list();
		} else if(type.equals("PENJUALAN")){
			all = session.createQuery("from Penjualan order by KODE").list();			
		}
		
		return all;
	}
	
	@Override
	public Session getSession() {
		return this.session;
	}

	@Override
	public Object getBy(String nama) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
